//
//  MCNetworking.swift
//  MCComon
//
//  Created by sabrina on 2018/1/10.
//  Copyright © 2018年 yuanjuhong. All rights reserved.
//

import Foundation
import Alamofire
import SwiftyJSON

struct Platform {
    static let isSimulator: Bool = {
        var isSim = false
        #if arch(i386) || arch(x86_64)
            isSim = true
        #endif
        return isSim
    }()
}

enum MCNetworkingError {
    case MCNetworkingErrorNoConnet
}

public enum requestType : String{
    case POST = "POST"
    case GET = "GET"
}

public enum encodingTyple : String{
    case JSON = "json"
    case HTTP = "URL"
}

public enum serVerType{
    case user
    case normal
}



open class MCNetworking: NSObject {
    var headers : HTTPHeaders = [
        "Authorization": "Basic YnJvd3Nlcjo=",
        ]
    var baseNormalURl = "http://java.manxwork.com/"
    var baseUserURl = ""
    var mangaer : Session?
    public static let shareInstance : MCNetworking = {
        let  tool = MCNetworking()
        let configuration = URLSessionConfiguration.default
        configuration.timeoutIntervalForRequest = 60
        tool.mangaer = Session.init(configuration: configuration, delegate: SessionDelegate.init(), serverTrustManager: nil)
//        tool.mangaer = Alamofire.SessionManager(configuration: configuration)
        return tool
    }()
    
}

extension MCNetworking {
    public func request(requestType:requestType,encoding:encodingTyple,serve:serVerType,param:Dictionary<String, Any>?,headerCustom:Dictionary<String,String>?,urlString:String,complete:@escaping ((Any)->()),fail:@escaping ((String)->()),requestProgress:((Int64,Int64,Double)->())?) -> () {
        self.setUpConfig()
        let type : HTTPMethod?
        switch requestType {
        case .GET:
            type = .get
            break
        default:
            type = .post
            break
        }
        let ecodetype : ParameterEncoding?
        switch encoding {
        case .JSON:
            ecodetype = JSONEncoding.default
        default:
            ecodetype = URLEncoding.default
        }
        let urlrequest = (serve == .user) ? (baseUserURl + urlString) : (baseNormalURl + urlString)
        if headerCustom != nil {
            for (key,value) in headerCustom!{
                headers[key] = value
            }
        }
      
      let requestTask = mangaer!.request(urlrequest, method: type!, parameters: param,encoding: ecodetype! , headers: headers).responseJSON { (response) in
            if Platform.isSimulator {
                // Do one thing
                print("\n ***********************************************************************************\n \(String(describing: response.response))\n***************************************************************\n prama= \n \(String(describing: param))\n***************************************************************\n\(String(describing: response.value))")
            }
      
            switch response.result {
           
            case .success(let value):
                let json = JSON(value)
                if(json["code"].intValue != 0){
                    fail(json["message"].stringValue)
                }else{
                    complete(json)
                }
                break
                
            case .failure( let error):
                if error._code == NSURLErrorTimedOut{
                     print("请求超时：\(urlrequest)")
                     fail("请求超时")
                }else{
                     print("网络错误：\(urlrequest)")
                     fail("网络错误")
                }
               
                // 不知道为什么错了
            }
        }
        if requestProgress != nil {
            requestTask.downloadProgress { (progress) in
                // Progress
                requestProgress!(progress.completedUnitCount,progress.totalUnitCount,progress.fractionCompleted)
            }
        }
       

    }
    
    //恢复默认配置
    func setUpConfig()  {
//        if MCUserManager.shareInstance.token.count > 0 {
//            headers["Authorization"] = (MCUserManager.shareInstance.scretoken) + " " + MCUserManager.shareInstance.token
//        } else{
//            headers["Authorization"] = "Basic YnJvd3Nlcjo="
//        }
    }
}


